package org.dtrd.modules.archive.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.config.system.SystemState.ResponseState;
import org.dtrd.modules.archive.config.ArchiveConfig;
import org.dtrd.modules.archive.config.ArchiveConfig.ArchiveReportEnum;
import org.dtrd.modules.archive.entity.bean.*;
import org.dtrd.modules.archive.entity.bean.laboratory.*;
import org.dtrd.modules.archive.entity.bean.lifeway.*;
import org.dtrd.modules.archive.entity.po.*;
import org.dtrd.modules.archive.entity.request.ArchiveReportRequest;
import org.dtrd.modules.archive.entity.request.DeleteReport;
import org.dtrd.modules.archive.entity.request.GroupReport;
import org.dtrd.modules.archive.service.*;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.util.SchemeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.*;


/**
 * 患者档案接口, 每个患者的档案记录都只有一条
 *
 * @author zcli
 * @date 2021-09-25
 */
@Api(tags = "患者档案")
@ApiSort(value = 102)
@RestController
@RequestMapping(path = {"/102", "/dossier"})
@Slf4j
public class PatientDossierAPIController extends BaseController {
    @Autowired
    private IDtrdEntRdOverviewService overviewService;
    @Autowired
    private IDtrdEntRdPhysicalService physicalService;
    /**
     * 影像学
     */
    @Autowired
    private IDtrdEntRdIconographyService iconographyService;
    /**
     * 实验室检查
     */
    @Autowired
    private IDtrdEntRdLaboratoryService laboratoryService;
    @Autowired
    private IDtrdEntRdLifewayService lifewayService;
    @Autowired
    private IDtrdEntRdEducationService educationService;
    @Autowired
    private IDtrdEntRdComplicationService complicationService;
    @Autowired
    private IDtrdEntRdComorbidityService comorbidityService;
    /**
     * 既往病史
     */
    @Autowired
    private IDtrdEntRdAnamnesisService anamnesisService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private IDtrdEntRdArchiveReportService archiveReportService;

    //region--------------10糖尿病概况-------------
    @ApiOperation("查询糖尿病概况")
    @GetMapping("/10/1021002")
    public Result<?> getOverview(@RequestParam Integer patientId) {
        DtrdEntRdArchiveOverview overview = overviewService.getPatientDiabetesOverview(patientId);
        if (null != overview) {
            DtrdEntRdOverviewDTO overviewDTO = new DtrdEntRdOverviewDTO();
            BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveOverview.class, DtrdEntRdOverviewDTO.class, false);
            beanCopier.copy(overview, overviewDTO, null);
            String logContent = String.format("查询糖尿病概况，查询患者id：%d", patientId);
            baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
            return Result.OK(overviewDTO);
        } else {
            return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
        }
    }

    /**
     * @param overviewDTO
     * @return
     * @deprecated 使用 updateOverview
     */
    @Deprecated
    @ApiOperation("添加/修改糖尿病概况")
    @PostMapping("/10/1021001/deprecated")
    public Result<?> updateOverviewV0(@RequestBody @Validated DtrdEntRdOverviewDTO overviewDTO) {
        Integer dataId = overviewDTO.getDataId();
        int patientId = overviewDTO.getPatientId();
        DtrdEntRdArchiveOverview overview = overviewService.getPatientDiabetesOverview(patientId);
        if (overview != null) {
            // 更新记录
            if (dataId != null && dataId >= 1 && dataId.equals(overview.getDataId())) {
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdOverviewDTO.class, DtrdEntRdArchiveOverview.class, false);
                beanCopier.copy(overviewDTO, overview, null);
                overviewService.updateById(overview);
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } else {
            overview = new DtrdEntRdArchiveOverview();
            overview.setCreateTime(new Date());
            BeanCopier beanCopier = BeanCopier.create(DtrdEntRdOverviewDTO.class, DtrdEntRdArchiveOverview.class, false);
            beanCopier.copy(overviewDTO, overview, null);
            overviewService.save(overview);
        }
        // 更新关联的数据
        Integer diabetesType = overviewDTO.getDiabetesType();
        if (diabetesType != null) {
            DtrdEntRdPatient patient = patientService.getById(patientId);
            patient.setPatientsDiabetisType(diabetesType);
            patient.setPatientsConfirmedDate(overviewDTO.getDiabetesDiagnoseDate());
            patientService.updateById(patient);
        }
        String logContent = String.format("添加/修改糖尿病概况，编辑患者id：%d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return Result.OK();
    }

    @ApiOperation("添加/修改糖尿病概况")
    @PostMapping("/10/1021001")
    public Result<?> updateOverview(@RequestBody @Validated DtrdEntRdOverviewDTO overviewDTO) {
        boolean result = overviewService.saveOrUpdateRecord(overviewDTO);
        String logContent = String.format("添加/修改糖尿病概况，编辑患者id：%d", overviewDTO.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("确认糖尿病概况档案完成")
    @PostMapping("/10/1021003")
    public Result<?> confirmOverview(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveOverview archive = overviewService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveOverview.class).eq(DtrdEntRdArchiveOverview::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        archive.setIsFinished(isFinished);
        boolean result = overviewService.updateById(archive);
        String logContent = String.format("确认患者id：%d 糖尿病概况档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------10糖尿病概况-------------

    //region--------------11体格检查-------------
    @ApiOperation(value = "添加体格检查", notes = "多张报告图片用“|”分隔")
    @PostMapping("/11/1021101")
    public Result<?> updatePhysical(@RequestBody PhysicalDTO physicalDTO) {
        try {
            if (null != physicalDTO) {
                Integer dataId = null;
                if (physicalDTO.getDataId() != null) {
                    dataId = physicalDTO.getDataId();
                }
                int patientId = physicalDTO.getPatientId();
                DtrdEntRdArchivePhysical physical = physicalService.getOne(new LambdaQueryWrapper<>(DtrdEntRdArchivePhysical.class).eq(DtrdEntRdArchivePhysical::getPatientId, patientId).eq(DtrdEntRdArchivePhysical::getIsDel, 0));
                if (physical != null) { // 更新记录
                    if (dataId != null && dataId >= 1 && dataId.equals(physical.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(PhysicalDTO.class, DtrdEntRdArchivePhysical.class, false);
                        beanCopier.copy(physicalDTO, physical, null);
                        // 设置bmi
                        if (physical.getHeight() != null && physical.getWeight() != null) {
                            physical.setBmi(SchemeUtil.getBmi(physical.getHeight(), physical.getWeight()));
                        }
                        // 设置腰臀比
                        if (physical.getWaist() != null && physical.getHip() != null) {
                            physical.setWhratio(SchemeUtil.getWhratio(physical.getWaist(), physical.getHip()));
                        }
                        physicalService.updateById(physical);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else { // 新增记录
                    physical = new DtrdEntRdArchivePhysical();
                    physical.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(PhysicalDTO.class, DtrdEntRdArchivePhysical.class, false);
                    beanCopier.copy(physicalDTO, physical, null);
                    // 设置bmi
                    if (physical.getHeight() != null && physical.getWeight() != null) {
                        physical.setBmi(SchemeUtil.getBmi(physical.getHeight(), physical.getWeight()));
                    }
                    // 设置腰臀比
                    if (physical.getWaist() != null && physical.getHip() != null) {
                        physical.setWhratio(SchemeUtil.getWhratio(physical.getWaist(), physical.getHip()));
                    }
                    physicalService.save(physical);
                }
                String logContent = String.format("添加体格检查，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK();
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-体格检查异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("查询体格检查")
    @GetMapping("/11/1021102")
    public Result<?> getPhysical(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchivePhysical> physicalList = physicalService.list(Wrappers.lambdaQuery(DtrdEntRdArchivePhysical.class).eq(DtrdEntRdArchivePhysical::getPatientId, patientId).eq(DtrdEntRdArchivePhysical::getIsDel, 0).orderByDesc(DtrdEntRdArchivePhysical::getCreateTime));
            if (null != physicalList && !physicalList.isEmpty()) {
                DtrdEntRdArchivePhysical physical = physicalList.get(0);
                PhysicalDTO physicalDTO = new PhysicalDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchivePhysical.class, PhysicalDTO.class, false);
                beanCopier.copy(physical, physicalDTO, null);
                String logContent = String.format("查询体格检查，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(physicalDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案提格检查异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认体格检查档案完成")
    @PostMapping("/10/1021103")
    public Result<?> confirmPhysical(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchivePhysical archive = physicalService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchivePhysical.class).eq(DtrdEntRdArchivePhysical::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        Integer type = getIntParam(request.getType(), 1);
        switch (type) {
            case 1:
                archive.setBasicIsFinished(isFinished);
                break;
            case 2:
                archive.setEyeIsFinished(isFinished);
                break;
            case 3:
                archive.setSkinIsFinished(isFinished);
                break;
            case 4:
                archive.setDiabeticFootIsFinished(isFinished);
                break;
            case 5:
                archive.setOtherIsFinished(isFinished);
                break;
            default:
                break;
        }
        boolean result = physicalService.updateById(archive);
        String logContent = String.format("确认患者id：%d 体格检查档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------11体格检查-------------

    //region--------------12影像学检查-------------
    @ApiOperation(value = "添加影像学检查", notes = "多张报告图片用“|”分隔")
    @PostMapping("/12/1021201")
    public Result<?> updateIconography(@RequestBody DtrdEntRdIconographyDTO iconographyDTO) {
        try {
            if (null != iconographyDTO) {
                Integer dataId = null;
                if (iconographyDTO.getDataId() != null) {
                    dataId = iconographyDTO.getDataId();
                }
                int patientId = iconographyDTO.getPatientId();
                DtrdEntRdArchiveIconography iconography = iconographyService.getOne(new LambdaQueryWrapper<>(DtrdEntRdArchiveIconography.class).eq(DtrdEntRdArchiveIconography::getPatientId, patientId).eq(DtrdEntRdArchiveIconography::getIsDel, 0));
                if (iconography != null) { // 更新记录
                    if (dataId != null && dataId >= 1 && dataId.equals(iconography.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(DtrdEntRdIconographyDTO.class, DtrdEntRdArchiveIconography.class, false);
                        beanCopier.copy(iconographyDTO, iconography, null);
                        iconographyService.updateById(iconography);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else {
                    iconography = new DtrdEntRdArchiveIconography();
                    iconography.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(DtrdEntRdIconographyDTO.class, DtrdEntRdArchiveIconography.class, false);
                    beanCopier.copy(iconographyDTO, iconography, null);
                    iconographyService.save(iconography);
                }
                String logContent = String.format("添加影像学检查，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK();
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-影像学检查异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("查询影像学检查")
    @GetMapping("/12/1021202")
    public Result<?> getIconography(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveIconography> iconographyList = iconographyService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveIconography.class).eq(DtrdEntRdArchiveIconography::getPatientId, patientId).eq(DtrdEntRdArchiveIconography::getIsDel, 0).orderByDesc(DtrdEntRdArchiveIconography::getCreateTime));
            if (null != iconographyList && !iconographyList.isEmpty()) {
                DtrdEntRdArchiveIconography iconography = iconographyList.get(0);
                DtrdEntRdIconographyDTO iconographyDTO = new DtrdEntRdIconographyDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveIconography.class, DtrdEntRdIconographyDTO.class, false);
                beanCopier.copy(iconography, iconographyDTO, null);
                String logContent = String.format("查询影像学检查，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(iconographyDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案影像学检查异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认影像学检查档案完成")
    @PostMapping("/10/1021203")
    public Result<?> confirmIconography(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveIconography archive = iconographyService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveIconography.class).eq(DtrdEntRdArchiveIconography::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        archive.setIsFinished(isFinished);
        boolean result = iconographyService.updateById(archive);
        String logContent = String.format("确认患者id：%d 影像学检查档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------12影像学检查-------------

    //region--------------13实验室检查-------------
    @ApiOperation("查询实验室检查")
    @GetMapping("/13/1021302")
    public Result<?> getLaboratory(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveLaboratory> laboratoryList = laboratoryService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveLaboratory.class).eq(DtrdEntRdArchiveLaboratory::getPatientId, patientId).eq(DtrdEntRdArchiveLaboratory::getIsDel, 0).orderByDesc(DtrdEntRdArchiveLaboratory::getCreateTime));
            if (null != laboratoryList && !laboratoryList.isEmpty()) {
                DtrdEntRdArchiveLaboratory laboratory = laboratoryList.get(0);
                DtrdEntRdLaboratoryDTO laboratoryDTO = new DtrdEntRdLaboratoryDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveLaboratory.class, DtrdEntRdLaboratoryDTO.class, false);
                beanCopier.copy(laboratory, laboratoryDTO, null);
                String logContent = String.format("查询实验室检查，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(laboratoryDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案-实验室检查异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    /**
     * 实验室检查-修改血糖
     */
    @ApiOperation(value = "实验室检查-血糖检查")
    @PostMapping("/laboratory/sugar/update")
    @AutoLog(value = "实验室检查-血糖检查", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratorySugar(@RequestBody @Validated LaboratorySugarDTO request) {
        boolean result = laboratoryService.updateSugarRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 实验室检查-OGTT
     */
    @ApiOperation(value = "实验室检查-OGTT与胰岛功能")
    @PostMapping("/laboratory/ogtt/update")
    @AutoLog(value = "实验室检查-OGTT与胰岛功能", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratoryOgtt(@RequestBody @Validated LaboratoryOgttDTO request) {
        boolean result = laboratoryService.updateOgttRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 实验室检查-血脂
     */
    @ApiOperation(value = "实验室检查-血脂检查")
    @PostMapping("/laboratory/lipid/update")
    @AutoLog(value = "实验室检查-血脂检查", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratoryLipid(@RequestBody @Validated LaboratoryLipidDTO request) {
        boolean result = laboratoryService.updateLipidRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 实验室检查-肝功能
     */
    @ApiOperation(value = "实验室检查-肝功能")
    @PostMapping("/laboratory/liver/update")
    @AutoLog(value = "实验室检查-肝功能", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratoryLiver(@RequestBody @Validated LaboratoryLiverDTO request) {
        boolean result = laboratoryService.updateLiverRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 实验室检查-肾功能
     */
    @ApiOperation(value = "实验室检查-肾功能")
    @PostMapping("/laboratory/kidney/update")
    @AutoLog(value = "实验室检查-Kidney", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratoryKidney(@RequestBody @Validated LaboratoryKidneyDTO request) {
        boolean result = laboratoryService.updateKidneyRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 实验室检查-酮体检查
     */
    @ApiOperation(value = "实验室检查-酮体检查")
    @PostMapping("/laboratory/ketone/update")
    @AutoLog(value = "实验室检查-酮体检查", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratoryKetone(@RequestBody @Validated LaboratoryKetoneDTO request) {
        boolean result = laboratoryService.updateKetoneRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 实验室检查-血气分析
     */
    @ApiOperation(value = "实验室检查-血气分析")
    @PostMapping("/laboratory/blood/update")
    @AutoLog(value = "实验室检查-血气分析", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateLaboratoryBlood(@RequestBody @Validated LaboratoryBloodDTO request) {
        boolean result = laboratoryService.updateBloodRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }


    @ApiOperation(value = "添加实验室检查", notes = "多张报告图片用“|”分隔")
    @PostMapping("/13/1021301")
    public Result<?> updateLaboratory(@RequestBody DtrdEntRdLaboratoryDTO laboratoryDTO) {
        try {
            if (null != laboratoryDTO) {
                Integer dataId = null;
                if (laboratoryDTO.getDataId() != null) {
                    dataId = laboratoryDTO.getDataId();
                }
                int patientId = laboratoryDTO.getPatientId();
                DtrdEntRdArchiveLaboratory laboratory = laboratoryService.getOne(new LambdaQueryWrapper<>(DtrdEntRdArchiveLaboratory.class).eq(DtrdEntRdArchiveLaboratory::getPatientId, patientId).eq(DtrdEntRdArchiveLaboratory::getIsDel, 0));
                if (laboratory != null) { // 更新记录
                    if (dataId != null && dataId >= 1 && dataId.equals(laboratory.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(DtrdEntRdLaboratoryDTO.class, DtrdEntRdArchiveLaboratory.class, false);
                        beanCopier.copy(laboratoryDTO, laboratory, null);
                        laboratoryService.updateById(laboratory);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else {
                    laboratory = new DtrdEntRdArchiveLaboratory();
                    laboratory.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(DtrdEntRdLaboratoryDTO.class, DtrdEntRdArchiveLaboratory.class, false);
                    beanCopier.copy(laboratoryDTO, laboratory, null);
                    laboratoryService.save(laboratory);
                }
                String logContent = String.format("添加实验室检查，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK();
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-实验室检查异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认实验室检查档案完成")
    @PostMapping("/10/1021303")
    public Result<?> confirmLaboratory(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveLaboratory archive = laboratoryService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveLaboratory.class).eq(DtrdEntRdArchiveLaboratory::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        Integer type = getIntParam(request.getType(), 1);
        switch (type) {
            case 1:
                archive.setSugarIsFinished(isFinished);
                break;
            case 2:
                archive.setOgttIsFinished(isFinished);
                break;
            case 3:
                archive.setLipidsIsFinished(isFinished);
                break;
            case 4:
                archive.setLiverIsFinished(isFinished);
                break;
            case 5:
                archive.setKidneyIsFinished(isFinished);
                break;
            case 6:
                archive.setKetoneIsFinished(isFinished);
                break;
            case 7:
                archive.setGasIsFinished(isFinished);
                break;
            default:
                break;
        }
        boolean result = laboratoryService.updateById(archive);
        String logContent = String.format("确认患者id：%d 实验室检查档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------13实验室检查-------------

    //region --------------14生活方式-------------

    /**
     * 生活方式-饮食情况
     */
    @ApiOperation(value = "生活方式-饮食情况")
    @PostMapping("/14/lifeway/eating/update")
    @AutoLog(value = "生活方式-饮食情况", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateEatingLifeway(@RequestBody @Validated LifewayEatingDTO request) {
        boolean result = lifewayService.updateEatingRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 生活方式-饮酒情况
     */
    @ApiOperation(value = "生活方式-饮酒情况")
    @PostMapping("/14/lifeway/drinking/update")
    @AutoLog(value = "生活方式-饮酒情况", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateDrinkingLifeway(@RequestBody @Validated LifewayDrinkingDTO request) {
        boolean result = lifewayService.updateDrinkingRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 生活方式-吸烟情况
     */
    @ApiOperation(value = "生活方式-吸烟情况")
    @PostMapping("/14/lifeway/smoking/update")
    @AutoLog(value = "生活方式-饮酒情况", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateSmokingLifeway(@RequestBody @Validated LifewaySmokingDTO request) {
        boolean result = lifewayService.updateSmokingRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 生活方式-睡眠情况
     */
    @ApiOperation(value = "生活方式-睡眠情况")
    @PostMapping("/14/lifeway/sleep/update")
    @AutoLog(value = "生活方式-睡眠情况", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateSleepingLifeway(@RequestBody @Validated LifewaySleepDTO request) {
        boolean result = lifewayService.updateSleepingRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 生活方式-运动情况
     */
    @ApiOperation(value = "生活方式-运动情况")
    @PostMapping("/14/lifeway/exercise/update")
    @AutoLog(value = "生活方式-运动情况", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> updateSmokingLifeway(@RequestBody @Validated LifewayExerciseDTO request) {
        boolean result = lifewayService.updateExerciseRecord(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "查询最新的生活方式", response = LifewayDetail.class)
    @GetMapping("/14/lifeway")
    @AutoLog(value = "查询最新的生活方式列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getLifewayList(@RequestParam Integer patientId) {
        List<LifewayDetail> list = lifewayService.getArchiveLifewayList(patientId);
        if (list == null || list.isEmpty()) {
            return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
        }
        return Result.OK(list.get(0));
    }

    /**
     * @param patientId
     * @return
     * @deprecated 该查询方式已弃用，请使用/14/lifeway/list 进行查询
     */
    @ApiOperation("查询生活方式")
    @GetMapping("/14/1021402/deprecated")
    public Result<?> getLifeway(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveLifeway> lifewayList = lifewayService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveLifeway.class).eq(DtrdEntRdArchiveLifeway::getPatientId, patientId).eq(DtrdEntRdArchiveLifeway::getIsDel, 0).orderByDesc(DtrdEntRdArchiveLifeway::getCreateTime));
            if (null != lifewayList && !lifewayList.isEmpty()) {
                DtrdEntRdArchiveLifeway lifeway = lifewayList.get(0);
                LifewayDTO lifewayDTO = new LifewayDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveLifeway.class, LifewayDTO.class, false);
                beanCopier.copy(lifeway, lifewayDTO, null);
                lifewayDTO.setSportAvg(lifeway.getExerciseDurationHour());
                lifewayDTO.setSmokingAvg(lifeway.getSmokingAmount());
                lifewayDTO.setSportAvg(lifeway.getExerciseDurationHour());
                String logContent = String.format("查询生活方式，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(lifewayDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案-生活方式异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    /**
     * @param lifewayDTO
     * @return
     * @deprecated 添加生活方式的接口已更新，请使用分部分进行保存
     */
    @ApiOperation("添加生活方式")
    @PostMapping("/14/1021401")
    public Result<?> updateLifeway(@RequestBody LifewayDTO lifewayDTO) {
        try {
            if (null != lifewayDTO) {
                Integer dataId = null;
                if (lifewayDTO.getDataId() != null) {
                    dataId = lifewayDTO.getDataId();
                }
                int patientId = lifewayDTO.getPatientId();
                DtrdEntRdArchiveLifeway lifeway = lifewayService.getOne(new LambdaQueryWrapper<>(DtrdEntRdArchiveLifeway.class).eq(DtrdEntRdArchiveLifeway::getPatientId, patientId).eq(DtrdEntRdArchiveLifeway::getIsDel, 0));
                if (lifeway != null) {
                    // 更新记录
                    if (dataId != null && dataId >= 1 && dataId.equals(lifeway.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(LifewayDTO.class, DtrdEntRdArchiveLifeway.class, false);
                        beanCopier.copy(lifewayDTO, lifeway, null);
                        lifeway.setSmokingAmount(lifewayDTO.getSmokingAvg());
                        lifeway.setExerciseDurationHour(lifewayDTO.getSportAvg());
                        lifewayService.updateById(lifeway);
                    } else {
                        return error(SystemState.ResponseState.STATE_PARAMS_ERROR);
                    }
                } else {
                    lifeway = new DtrdEntRdArchiveLifeway();
                    lifeway.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(LifewayDTO.class, DtrdEntRdArchiveLifeway.class, false);
                    beanCopier.copy(lifewayDTO, lifeway, null);
                    lifeway.setSmokingAmount(lifewayDTO.getSmokingAvg());
                    lifeway.setExerciseDurationHour(lifewayDTO.getSportAvg());
                    lifewayService.save(lifeway);
                }
                String logContent = String.format("添加生活方式，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK();
            } else {
                return error(SystemState.ResponseState.STATE_PARAMS_ERROR);
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-生活方式异常", e);
            return error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
        }
    }

    @ApiOperation("确认生活方式档案完成")
    @PostMapping("/10/1021403")
    public Result<?> confirmLifeway(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveLifeway archive = lifewayService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveLifeway.class).eq(DtrdEntRdArchiveLifeway::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        Integer type = getIntParam(request.getType(), 1);
        switch (type) {
            case 1:
                archive.setSportIsFinished(isFinished);
                break;
            case 2:
                archive.setWineIsFinished(isFinished);
                break;
            case 3:
                archive.setSmokeIsFinished(isFinished);
                break;
            case 4:
                archive.setSleepIsFinished(isFinished);
                break;
            default:
                break;
        }
        boolean result = lifewayService.updateById(archive);
        String logContent = String.format("确认患者id：%d 生活方式档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    //endregion --------------14生活方式-------------

    //region --------------15糖尿病教育情况-------------
    @ApiOperation("查询教育情况")
    @GetMapping("/15/1021502")
    public Result<?> getEducation(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveEducation> educationList = educationService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveEducation.class).eq(DtrdEntRdArchiveEducation::getPatientId, patientId).eq(DtrdEntRdArchiveEducation::getIsDel, 0).orderByDesc(DtrdEntRdArchiveEducation::getCreateTime));
            if (null != educationList && !educationList.isEmpty()) {
                DtrdEntRdArchiveEducation education = educationList.get(0);
                DtrdEntRdEducationDTO educationDTO = new DtrdEntRdEducationDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveEducation.class, DtrdEntRdEducationDTO.class, false);
                beanCopier.copy(education, educationDTO, null);
                String logContent = String.format("查询教育情况，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(educationDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案-糖尿病教育情况异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("添加/修改教育情况")
    @PostMapping("/15/1021501")
    public Result<?> updateEducation(@RequestBody DtrdEntRdEducationDTO educationDTO) {
        try {
            if (null != educationDTO) {
                Integer dataId = null;
                if (educationDTO.getDataId() != null) {
                    dataId = educationDTO.getDataId();
                }
                Integer patientId = educationDTO.getPatientId();
                DtrdEntRdArchiveEducation education = educationService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveEducation.class).eq(DtrdEntRdArchiveEducation::getPatientId, patientId).eq(DtrdEntRdArchiveEducation::getIsDel, 0));
                if (null != education) {
                    if (dataId != null && dataId >= 1 && dataId.equals(education.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(DtrdEntRdEducationDTO.class, DtrdEntRdArchiveEducation.class, false);
                        beanCopier.copy(educationDTO, education, null);
                        educationService.updateById(education);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else {
                    education = new DtrdEntRdArchiveEducation();
                    education.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(DtrdEntRdEducationDTO.class, DtrdEntRdArchiveEducation.class, false);
                    beanCopier.copy(educationDTO, education, null);
                    educationService.save(education);
                }
                String logContent = String.format("添加/修改教育情况，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK(education.getDataId());
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-糖尿病教育情况异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认糖尿病教育档案完成")
    @PostMapping("/10/1021503")
    public Result<?> confirmEducation(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveEducation archive = educationService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveEducation.class).eq(DtrdEntRdArchiveEducation::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        archive.setIsFinished(isFinished);
        boolean result = educationService.updateById(archive);
        String logContent = String.format("确认患者id：%d 糖尿病教育档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion --------------15糖尿病教育情况-------------

    //region--------------16糖尿病并发症-------------
    @ApiOperation("查询糖尿病并发症")
    @GetMapping("/16/1021602")
    public Result<?> getComplication(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveComplication> complicationList = complicationService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveComplication.class).eq(DtrdEntRdArchiveComplication::getPatientId, patientId).orderByDesc(DtrdEntRdArchiveComplication::getCreateTime));
            if (null != complicationList && !complicationList.isEmpty()) {
                DtrdEntRdArchiveComplication complication = complicationList.get(0);
                ComplicationDTO complicationDTO = new ComplicationDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveComplication.class, ComplicationDTO.class, false);
                beanCopier.copy(complication, complicationDTO, null);
                String logContent = String.format("查询并发症，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(complicationDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案-并发症异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("添加/修改糖尿病并发症")
    @PostMapping("/16/1021601")
    public Result<?> updateComplication(@RequestBody ComplicationDTO complicationDTO) {
        try {
            if (null != complicationDTO) {
                Integer dataId = null;
                if (complicationDTO.getDataId() != null) {
                    dataId = complicationDTO.getDataId();
                }
                int patientId = complicationDTO.getPatientId();
                DtrdEntRdArchiveComplication complication = complicationService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveComplication.class).eq(DtrdEntRdArchiveComplication::getPatientId, patientId));
                if (null != complication) {
                    if (dataId != null && dataId >= 1 && dataId.equals(complication.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(ComplicationDTO.class, DtrdEntRdArchiveComplication.class, false);
                        beanCopier.copy(complicationDTO, complication, null);
                        complicationService.updateById(complication);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else {
                    complication = new DtrdEntRdArchiveComplication();
                    complication.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(ComplicationDTO.class, DtrdEntRdArchiveComplication.class, false);
                    beanCopier.copy(complicationDTO, complication, null);
                    complicationService.save(complication);
                }
                String logContent = String.format("添加/修改并发症，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK(complication.getDataId());
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-并发症异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认糖尿病并发症档案完成")
    @PostMapping("/10/1021603")
    public Result<?> confirmComplication(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveComplication archive = complicationService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveComplication.class).eq(DtrdEntRdArchiveComplication::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        Integer type = getIntParam(request.getType(), 1);
        switch (type) {
            case 1:
                archive.setKidneyIsFinished(isFinished);
                break;
            case 2:
                archive.setRetinaIsFinished(isFinished);
                break;
            case 3:
                archive.setPeripheralNeuropathyIsFinished(isFinished);
                break;
            case 4:
                archive.setCardiovascularIsFinished(isFinished);
                break;
            case 5:
                archive.setDigestionIsFinished(isFinished);
                break;
            case 6:
                archive.setUrinaryIsFinished(isFinished);
                break;
            case 7:
                archive.setOtherNeuropathiesIsFinished(isFinished);
                break;
            case 8:
                archive.setLowerLimbsIsFinished(isFinished);
                break;
            case 9:
                archive.setDiabeticFootIsFinished(isFinished);
                break;
            case 10:
                archive.setDkaIsFinished(isFinished);
                break;
            default:
                break;
        }
        boolean result = complicationService.updateById(archive);
        String logContent = String.format("确认患者id：%d 糖尿病并发症档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------16糖尿病并发症-------------

    //region--------------17糖尿病合并症-------------
    @ApiOperation(value = "查询合并症", response = DtrdEntRdComorbidityDTO.class)
    @GetMapping("/17/1021702")
    public Result<?> getComorbidity(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveComorbidity> comorbidityList = comorbidityService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveComorbidity.class).eq(DtrdEntRdArchiveComorbidity::getPatientId, patientId));
            if (null != comorbidityList && !comorbidityList.isEmpty()) {
                DtrdEntRdArchiveComorbidity comorbidity = comorbidityList.get(0);
                DtrdEntRdComorbidityDTO comorbidityDTO = new DtrdEntRdComorbidityDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveComorbidity.class, DtrdEntRdComorbidityDTO.class, false);
                beanCopier.copy(comorbidity, comorbidityDTO, null);
                String logContent = String.format("查询合并症，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(comorbidityDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案-合并症异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("添加/修改合并症")
    @PostMapping("/17/1021701")
    public Result<?> updateComorbidity(@RequestBody DtrdEntRdComorbidityDTO comorbidityDTO) {
        try {
            if (null != comorbidityDTO) {
                Integer dataId = null;
                if (comorbidityDTO.getDataId() != null) {
                    dataId = comorbidityDTO.getDataId();
                }
                int patientId = comorbidityDTO.getPatientId();
                DtrdEntRdArchiveComorbidity comorbidity = comorbidityService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveComorbidity.class).eq(DtrdEntRdArchiveComorbidity::getPatientId, patientId));
                if (null != comorbidity) {
                    if (dataId != null && dataId >= 1 && dataId.equals(comorbidity.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(DtrdEntRdComorbidityDTO.class, DtrdEntRdArchiveComorbidity.class, false);
                        beanCopier.copy(comorbidityDTO, comorbidity, null);
                        comorbidityService.updateById(comorbidity);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else {
                    comorbidity = new DtrdEntRdArchiveComorbidity();
                    comorbidity.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(DtrdEntRdComorbidityDTO.class, DtrdEntRdArchiveComorbidity.class, false);
                    beanCopier.copy(comorbidityDTO, comorbidity, null);
                    comorbidityService.save(comorbidity);
                }
                String logContent = String.format("添加/修改合并症，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK(comorbidity.getDataId());
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-合并症异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认糖尿病合并症档案完成")
    @PostMapping("/10/1021703")
    public Result<?> confirmComorbidity(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveComorbidity archive = comorbidityService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveComorbidity.class).eq(DtrdEntRdArchiveComorbidity::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        Integer type = getIntParam(request.getType(), 1);
        switch (type) {
            case 1:
                archive.setHighPressureIsFinished(isFinished);
                break;
            case 2:
                archive.setHyperlipidemiaIsFinished(isFinished);
                break;
            case 3:
                archive.setCardiovascularIsFinished(isFinished);
                break;
            case 4:
                archive.setCerebrovascularIsFinished(isFinished);
                break;
            case 5:
                archive.setBloodVesselsAroundIsFinished(isFinished);
                break;
            default:
                break;
        }
        boolean result = comorbidityService.updateById(archive);
        String logContent = String.format("确认患者id：%d 糖尿病合并症档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------17糖尿病合并症-------------

    //region--------------18既往病史和过敏史-------------
    @ApiOperation("查询既往病史过敏史")
    @GetMapping("/18/1021802")
    public Result<?> getAnamnesis(@RequestParam Integer patientId) {
        try {
            List<DtrdEntRdArchiveAnamnesis> anamnesisList = anamnesisService.list(Wrappers.lambdaQuery(DtrdEntRdArchiveAnamnesis.class).eq(DtrdEntRdArchiveAnamnesis::getPatientId, patientId).orderByDesc(DtrdEntRdArchiveAnamnesis::getCreateTime));
            if (null != anamnesisList && !anamnesisList.isEmpty()) {
                DtrdEntRdArchiveAnamnesis anamnesis = anamnesisList.get(0);
                AnamnesisDTO anamnesisDTO = new AnamnesisDTO();
                BeanCopier beanCopier = BeanCopier.create(DtrdEntRdArchiveAnamnesis.class, AnamnesisDTO.class, false);
                beanCopier.copy(anamnesis, anamnesisDTO, null);
                String logContent = String.format("查询既往病史过敏史，查询患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
                return Result.OK(anamnesisDTO);
            } else {
                return Result.error(SystemState.ResponseState.STATE_NO_RECORD.getCode(), SystemState.ResponseState.STATE_NO_RECORD.getMsg());
            }
        } catch (Exception e) {
            log.error("获取患者健康档案-既往病史和过敏史异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("添加/修改既往病史过敏史")
    @PostMapping("/18/1021801")
    public Result<?> updateAnamnesis(@RequestBody AnamnesisDTO anamnesisDTO) {
        try {
            if (null != anamnesisDTO) {
                Integer dataId = null;
                if (anamnesisDTO.getDataId() != null) {
                    dataId = anamnesisDTO.getDataId();
                }
                int patientId = anamnesisDTO.getPatientId();
                DtrdEntRdArchiveAnamnesis anamnesis = anamnesisService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveAnamnesis.class).eq(DtrdEntRdArchiveAnamnesis::getPatientId, patientId).eq(DtrdEntRdArchiveAnamnesis::getIsDel, 0));
                if (null != anamnesis) {
                    if (dataId != null && dataId >= 1 && dataId.equals(anamnesis.getDataId())) {
                        BeanCopier beanCopier = BeanCopier.create(AnamnesisDTO.class, DtrdEntRdArchiveAnamnesis.class, false);
                        beanCopier.copy(anamnesisDTO, anamnesis, null);
                        anamnesisService.updateById(anamnesis);
                    } else {
                        return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
                    }
                } else {
                    anamnesis = new DtrdEntRdArchiveAnamnesis();
                    anamnesis.setCreateTime(new Date());
                    BeanCopier beanCopier = BeanCopier.create(AnamnesisDTO.class, DtrdEntRdArchiveAnamnesis.class, false);
                    beanCopier.copy(anamnesisDTO, anamnesis, null);
                    anamnesisService.save(anamnesis);
                }
                String logContent = String.format("添加/修改既往病史过敏史，编辑患者id：%d", patientId);
                baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
                return Result.OK();
            } else {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            }
        } catch (Exception e) {
            log.error("编辑患者健康档案-既往病史过敏史异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    @ApiOperation("确认既往病史和过敏史档案完成")
    @PostMapping("/10/1021803")
    public Result<?> confirmAnamnesis(@RequestBody ConfirmBean request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer isFinished = request.getIsFinished();
        if (isFinished != Constant.FINISHED && isFinished != Constant.UN_FINISHED) {
            return error(STATE_PARAMS_ERROR);
        }
        DtrdEntRdArchiveAnamnesis archive = anamnesisService.getOne(Wrappers.lambdaQuery(DtrdEntRdArchiveAnamnesis.class).eq(DtrdEntRdArchiveAnamnesis::getPatientId, patientId));
        if (archive == null) {
            return error(STATE_PARAMS_ERROR);
        }
        Integer type = getIntParam(request.getType(), 1);
        switch (type) {
            case 1:
                archive.setHypoglycemiaIsFinished(isFinished);
                break;
            case 2:
                archive.setGoutIsFinished(isFinished);
                break;
            case 3:
                archive.setKetosisIsFinished(isFinished);
                break;
            case 4:
                archive.setHypertonicIsFinished(isFinished);
                break;
            case 5:
                archive.setLacticAcidosisIsFinished(isFinished);
                break;
            case 6:
                archive.setKidneyIsFinished(isFinished);
                break;
            case 7:
                archive.setOtherIsFinished(isFinished);
            default:
                break;
        }
        boolean result = anamnesisService.updateById(archive);
        String logContent = String.format("确认患者id：%d 既往病史和过敏史档案完成", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
    //endregion--------------18既往病史和过敏史-------------

    //--------------region 报告单 --------------

    /**
     * 保存报告单
     */
    @ApiOperation(value = "保存报告单")
    @PostMapping("/report/save")
    @AutoLog(value = "保存报告单", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> saveReport(@RequestBody @Validated ReportInfo report) {
        boolean result = archiveReportService.saveOrUpdateReport(report);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 删除报告单
     */
    @ApiOperation(value = "删除报告单")
    @PostMapping("/report/del")
    @AutoLog(value = "删除报告单", operateType = OPERATE_TYPE_DELETE)
    public Result<?> deleteReport(@RequestBody @Validated DeleteReport request) {
        boolean result = archiveReportService.removeByIds(request.getDataIdList());
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    /**
     * 查询患者报告单
     */
    @ApiOperation(value = "查询报告单", response = ReportInfo.class)
    @PostMapping("/report/query")
    @AutoLog(value = "查询报告单", operateType = OPERATE_TYPE_DELETE)
    public Result<?> getPatientReport(@RequestBody ArchiveReportRequest request) {
        List<ReportInfo> reportList = archiveReportService.getPatientReport(request.getPatientId(), request.getType());
        return Result.OK(reportList);
    }

    /**
     * 批量分组患者报告单
     */
    @ApiOperation(value = "批量分组患者报告单")
    @PostMapping("/report/group")
    @AutoLog(value = "批量分组患者报告单", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> groupPatientReport(@RequestBody @Validated GroupReport report) {
        boolean result = archiveReportService.groupPatientReport(report.getPatientId(), report.getReportIdList(), report.getType());
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }


    //--------------endregion 报告单 --------------
}
